package org.dearsor.elective.controller;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dearsor.elective.model.Person;
import org.dearsor.elective.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
	
	@PersistenceContext private EntityManager em;
	
	private Person user;
	
	private static final Log log = LogFactory.getLog(LoginController.class);
	
	@RequestMapping(value = "/loginForm",method = RequestMethod.GET)
	public String loginForm(@ModelAttribute("user") Student user) {
		user = new Student();
//		em.persist(user);
		return "loginForm";
	}
	
	
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public String doLogin(@ModelAttribute("user") Person user,HttpServletRequest request) {
		setUser(user);
		if (authenticate()) {
			Student student = em.find(Student.class, getUser().getId());
			//				BeanUtils.copyProperties(student, user);
							request.getSession().setAttribute("currentUser", student);
//							return "prompt";
							return "redirect:/courseList";
		}
		return "loginFailed";
	}
	
	public boolean authenticate() throws RuntimeException {
		if (getUser() == null || getUser().getName() == null || getUser().getName().length() < 1 || getUser().getPassword() == null || getUser().getPassword().length() < 1) {
			return false;
		}
		try {

			Person person = (Person) em
					.createQuery(
							"select u from Person u where u.name = :uid and u.password = :pwd")
					.setParameter("uid", getUser().getName()).setParameter("pwd",
							getUser().getPassword()).getSingleResult();
			setUser(person);
			return true;
		} catch (EntityNotFoundException e) {
			// TODO: handle exception
			log.info(e.getMessage());
			return false;
		} catch (NonUniqueResultException e) {
			// TODO: handle exception
			log.info(e.getMessage());
			return false;
		} catch (javax.persistence.NoResultException e) {
			// TODO: handle exception
			log.info(e.getMessage());
			return false;
		} catch (Exception e) {
			// TODO: handle exception
			log.info("出现了不期望的异常",e);
			return false;
		}
		
	}
	
	@RequestMapping("/logout")
	public String doLogout(HttpServletRequest request) {
		if (request.getSession().getAttribute("currentUser") != null) {
			// TODO Auto-generated method stub
			request.getSession().removeAttribute("currentUser");
		}
		return "welcome";
	}


	protected void setUser(Person user) {
		this.user = user;
	}


	protected Person getUser() {
		return user;
	}

}
